package com.liujiajin;

import java.io.File;
import java.net.URL;

import com.mylib.Myclass;

public class ClassLoadDemo2 {
	public static void main(String[] args) throws Exception {
		// 创建一个自定义类加载器
    	File libPath = new File(Constants.LIB);

    	String repository = (new URL("file", null, libPath.getCanonicalPath() + File.separator)).toString();  	
    	// 创建两个自定义类加载器
        URL[] urls1 = {new URL(repository + "mylib-1.0.jar")};
        URL[] urls2 = {new URL(repository + "mylib-2.0.jar")};

        try (CustomClassLoader classLoader1 = new CustomClassLoader(urls1);
				CustomClassLoader classLoader2 = new CustomClassLoader(urls2)) {
			// 加载两个版本的 MyClass
			Class<?> myClass1 = classLoader1.loadClass("com.mylib.Myclass");
			Class<?> myClass2 = classLoader2.loadClass("com.mylib.Myclass");
			
			// 创建两个版本的 MyClass 实例
			Object instance1 = myClass1.getDeclaredConstructor().newInstance();
			Object instance2 = myClass2.getDeclaredConstructor().newInstance();

			// 调用方法
			myClass1.getMethod("printVersion").invoke(instance1);
			myClass2.getMethod("printVersion").invoke(instance2);

			// 演示类冲突
			System.out.println("instance1 instanceof MyClass: " + (instance1 instanceof Myclass));
			System.out.println("instance2 instanceof MyClass: " + (instance2 instanceof Myclass));
			System.out.println("myClass1 == myClass2: " + (myClass1 == myClass2));
		}
	}

}
